<template>
  <el-dialog
    :title="record !== undefined ? '编辑商品分类' : '新增商品分类'"
    width="50%"
    :visible="visible"
    :confirmLoading="confirmLoading"
    :maskClosable="false"
    :destroyOnClose="true"
    append-to-body
    @close="handleCancel"
  >
    <a-spin :spinning="confirmLoading">
      <a-form :form="form">
        <a-form-item label="分类名称" :labelCol="labelCol" :wrapperCol="wrapperCol">
          <a-input
            v-decorator="['name', {rules: [{required: true, min: 2, message: '请输入至少2个字符'}]}]"
          />
        </a-form-item>
        <!-- zIndex: 9999 -->
        <a-form-item label="上级分类" :labelCol="labelCol" :wrapperCol="wrapperCol">
          <a-tree-select
            :treeData="categoryListTree"
            :dropdownStyle="{ maxHeight: '400px', overflow: 'auto' , }"
            :getPopupContainer="(node) => node.parentNode"
            allowClear
            treeDefaultExpandAll
            v-decorator="['parentId', {initialValue: 0}]"
          >
        </a-tree-select>
        </a-form-item>
        <a-form-item label="分类图片" :labelCol="labelCol" :wrapperCol="wrapperCol">
          <!-- <SelectImage v-decorator="['image_id']" /> -->
          <el-upload
                  v-if="!imageUrl"
                  class="uploader"
                  :action="uploadAction"
                  :on-success="handleSuccess"
                  :headers="headers"
                  :show-file-list="false"
                  :before-upload="beforeUpload"
                  list-type="picture-card"
                  :multiple="false"
                >
                <i slot="default" class="el-icon-plus"></i>
                </el-upload>
                <div
                  v-else
                  style="position: relative"
                  class="attachment_view"
                >
                  <el-image
                    style="width: 100%; height: 100%; border-radius: 3px"
                    :src="imageUrl"
                    :preview-src-list="[imageUrl]"
                  >
                  </el-image>
                  <div class="attachment_mask">
                    <img src="@/assets/att_del.png" style="width: 100%;height: 100%" @click="delImg()" />
                  </div>
                  <div class="attachment_mask_pre">
                    <img src="@/assets/att_pre.png" />
                  </div>
                </div>
        </a-form-item>
        <a-form-item label="状态" :labelCol="labelCol" :wrapperCol="wrapperCol" extra="用户端是否展示">
          <a-radio-group v-decorator="['status', {initialValue: 1, rules: [{required: true}]}]">
            <a-radio :value="1">显示</a-radio>
            <a-radio :value="0">隐藏</a-radio>
          </a-radio-group>
        </a-form-item>
        <a-form-item label="排序" :labelCol="labelCol" :wrapperCol="wrapperCol" extra="数字越小越靠前">
          <a-input-number
            :min="0"
            v-decorator="['sort', {initialValue: 100, rules: [{required: true, message: '请输入至少1个数字'}, { validator: this.validateInteger }]}]"
          />
        </a-form-item>
      </a-form>
    </a-spin>
    <div slot="footer" class="dialog-footer">
      <el-button size="small" type="primary" @click="handleSubmit">保存</el-button>
      <el-button size="small"  @click="visible = false">取消</el-button>
    </div>
  </el-dialog>
</template>

<script>
// import * as Api from '@/api/category'
// import { SelectImage } from '@/components'
// import CategoryModel from '@/common/model/Category'
import { getAction, putAction, deleteAction, downPostFile, postAction } from '@/api/manage'
import { ACCESS_TOKEN, TENANT_ID, ACCOUNT_BOOK } from '@/store/mutation-types'
import Vue from 'vue'

export default {
  components: {
    // SelectImage
  },
  props: {
    // 分类列表
    categoryList: {
      type: Array,
      required: true
    }
  },
  data () {
    return {
      // uploadAction: window._CONFIG['domianURL'] + '/sys/common/upload',
      uploadAction: window._CONFIG['domianURL'] + '/goods/yoshopGoods/importFile',

      
     headers: { 'X-Access-Token': Vue.ls.get(ACCESS_TOKEN) },
     imageUrl: '',
     imageId: '',
      // 账套id
      accountBookId:Vue.ls.get(ACCOUNT_BOOK).id,
      // 对话框标题
      title: '',
      // 标签布局属性
      labelCol: {
        span: 7
      },
      // 输入框布局属性
      wrapperCol: {
        span: 13
      },
      // modal(对话框)是否可见
      visible: false,
      // modal(对话框)确定按钮 loading
      confirmLoading: false,
      // 当前表单元素
      form: this.$form.createForm(this),

      // 上级分类列表
      categoryListTree: [],
      record: undefined,
    }
  },
  methods: {

    // 验证是否为整数的方法
    validateInteger(rule, value, callback) {
      if (!Number.isInteger(value)) {
        callback(new Error('请输入整数'));
      } else {
        callback();
      }
    },

    // 显示对话框
    add (record) {
      console.log(record,'record',record !== undefined)
      // 显示窗口
      this.visible = true
      // 获取分类列表
      this.getCategoryList()
      if(record !== undefined){
         // 当前分类记录
      this.record = record
      // 设置默认值
      this.setFieldsValue()
      }
    },

     // 设置默认值
     setFieldsValue () {
      console.log(this.record,'11this.record')
      const { record, form: { setFieldsValue } } = this
      // 设置表单内容
      this.$nextTick(() => {
        setFieldsValue(_.pick(record, ['name', 'parentId', 'status', 'sort']))
        this.imageUrl = record.imageUrl
        this.imageId = record.imageId
      })
    },

    beforeUpload(file) {
      let type = file.type.toLowerCase()
      const isJPG = type.includes('png') || type.includes('jpeg') || type.includes('jpg')
      const isLt2M = file.size / 1024 / 1024 < 2
      if (!isJPG) {
        this.$message.error('请上传png/jpg/jpeg格式的图片!')
      }
      if (!isLt2M) {
        this.$message.error('上传图片大小不能超过 2MB!')
      }
      return isJPG && isLt2M
    },
    handleSuccess(e) {
      console.log(e)
      if (e.success) {
        console.log(e,'e')
        this.imageUrl = e.result.domain + '/' + e.result.filePath
        // this.imageUrl = e.result.filePath
        this.imageId = e.result.fileId
        console.log(this.imageUrl,'this.imageUrl')
      }
    },
    delImg() {
      this.imageUrl = ''
      this.imageId = ''
    },

    // 获取分类列表
    getCategoryList () {
      const { categoryList } = this
      console.log(categoryList,'获取到的categoryList')
      // 格式化分类列表
      const selectList = this.formatTreeData(categoryList)
      console.log(selectList,'selectList')
      // 顶级分类
      this.categoryListTree = [{
        title: '顶级分类',
        key: 0,
        value: 0,
        children: [...selectList]
      }]
      // ].concat(selectList)
      console.log(this.categoryListTree,'this.categoryListTree')
    },

     /**
   * 格式化分类列表
   * @param {*} list 分类数据源
   * @param {*} disabled
   */
  formatTreeData (list, disabledParentId = null, disabled = false) {
    const data = []
    list.forEach(item => {
      // 新的元素
      const netItem = {
        title: item.name,
        key: item.categoryId,
        value: item.categoryId
      }
      // 禁用的分类
      if (
        [item.categoryId, item.categoryId].includes(disabledParentId) ||
        disabled === true
      ) {
        netItem.disabled = true
      }
      // 递归整理子集
      if (item.children && item.children.length) {
        netItem['children'] = this.formatTreeData(item['children'], disabledParentId, netItem.disabled)
      }
      data.push(netItem)
    })
    return data
  },

    // 确认按钮
    handleSubmit (e) {
      e.preventDefault()
      // 表单验证
      const { form: { validateFields } } = this
      validateFields((errors, values) => {
        // 提交到后端api
        if (!errors) {
          values.imageUrl = this.imageUrl
          values.imageId = this.imageId
          this.onFormSubmit(values)
        }
      })
    
    },

    // validate()
    //   .then((res) => {
    //     let formStateSwitch = { ...formState.value }
    //     requestAddOrEdit(formStateSwitch)
    //   })
    //   .catch((err) => {
    //     console.log('error', err)
    //   })

    // 关闭对话框事件
    handleCancel () {
      console.log('关闭')
      this.visible = false
      this.form.resetFields()
      this.imageUrl = ''
      this.imageId = ''
      this.record = undefined
    },

    // 提交到后端api
    onFormSubmit (values) {
      this.confirmLoading = true
      if(this.record !== undefined){
        putAction('/yoshopCategory/edit',{ ...values,storeId: this.accountBookId,categoryId: this.record.categoryId })
          .then((result) => {
          if (result.success) {
            // 显示成功
            this.$message.success(result.message, 1.5)
            // 关闭对话框事件
            this.handleCancel()
            // 通知父端组件提交完成了
            this.$emit('handleSubmit', values)
          } else {
            this.$message.error(result.message, 1.5)
          }
        })
        .finally((result) => {
          this.confirmLoading = false
        })
      }else{
        postAction('/yoshopCategory/add',{ ...values,storeId: this.accountBookId })
        .then((result) => {
          if (result.success) {
            // 显示成功
            this.$message.success(result.message, 1.5)
            // 关闭对话框事件
            this.handleCancel()
            // 通知父端组件提交完成了
            this.$emit('handleSubmit', values)
          } else {
            this.$message.error(result.message, 1.5)
          }
        })
        .finally((result) => {
          this.confirmLoading = false
        })
      }
        
    }

  }
}
</script>
<style lang="scss" scoped>
::v-deep .el-dialog__footer{
   border-top: 1px solid #e3e3e3;
}
::v-deep .el-upload--picture-card{
  width: 80px;
  height: 80px;
  display: flex;
  align-items: center;
  justify-content: center;
}
.uploader {
  width: 80px;
  height: 80px;
  overflow: hidden;
  position: relative;
}
.attachment_view {
  border: 1px dashed white;
  width: 80px;
  height: 80px;
  background-color: #f6f6f6;
  line-height: 40px;
  text-align: center;
}
.attachment_mask {
  z-index: 2;
  position: absolute;
  right: 0;
  top: 0;
  width: 12px;
  height: 12px;
  display: flex;
  align-items: center;
}
.attachment_mask_pre {
  z-index: 1;
  position: absolute;
  display: flex;
  align-items: center;
  pointer-events: none;
  right: 0;
  top: 0;
  left: 0;
  bottom: 0;
  // backdrop-filter: blur(1px);
  img{
    position: absolute;
    width: 14px;
    height: 14px;
    transform: translate(-50%, -50%);
    top: 50%;
    left: 50%;
  }
}
</style>
